﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services.Protocols;
using System.Web.UI.WebControls;
using MedicWeb.forms.Directory;
using MedicWeb.MedicService;
using MedicWeb.MedRegService;

namespace MedicWeb.forms.Editors {
    public partial class DoctorEdit : SessionPage {
        Doctor doctor;

        protected void Page_Load(object sender, EventArgs e) {
            string id = Request.QueryString["id"];
            Form.Action = ResolveUrl("~/forms/Editors/DoctorEdit.aspx");
            Form.Attributes["postback"] = ""+IsPostBack;
            var ms = new MainService();
            if (id != null) {
                Form.Action += "?id=" + id;
                doctor = ms.LoadDoctor(GetSession(), int.Parse(id));
            } else {
                if (IsPostBack) {
                    doctor = (Doctor) Session["newdoctor"];
                }
                if (doctor == null) {
                    doctor = new Doctor();
                    doctor.AcademicTitle = new AcademicTitle();
                    doctor.Degree = new Degree();
                    doctor.GroupExp = new GroupExp();
                    doctor.Institution = new Institution();
                    doctor.InstitutionType = new InstitutionType();
                    doctor.Job = new Job();
                    doctor.Job2 = new Job();
                    doctor.Locality = new Locality();
                    doctor.NewClass = new Class();
                    doctor.NewSpeciality = new Speciality();
                    doctor.OldClass = new Class();
                    doctor.OldSpeciality = new Speciality();
                    doctor.Order = new Order();
                    doctor.Region = new Region();
                    doctor.RegstrationDate = DateTime.Now;
                    Session["newdoctor"] = doctor;
                }
            }

            if (IsPostBack) {
                var allKeys = Request.Form.AllKeys;
                doctor.AcademicTitle.Id = convertToInt(Request.Form["comboAcademicTitle"]);
                doctor.OldClass.Id = convertToInt(Request.Form["comboClass"]);
                doctor.NewClass.Id = convertToInt(Request.Form["comboClassNew"]);
                doctor.Degree.Id = convertToInt(Request.Form["comboDegree"]);
                //doctor.Institution.Id = convertToInt(Request.Form["comboInstitution"]);
                doctor.Job.Id = convertToInt(Request.Form["comboJob"]);
                doctor.Job2.Id = convertToInt(Request.Form["comboJob2"]);
                //doctor.Locality.Id = convertToInt(Request.Form["comboLocality"]);
                //doctor.Region.Id = convertToInt(Request.Form["comboRegion"]);
                doctor.OldSpeciality.Id = convertToInt(Request.Form["comboSpec"]);
                doctor.NewSpeciality.Id = convertToInt(Request.Form["comboSpecNew"]);
                doctor.ContractNumber = convertToInt(Request.Form["tfContractNumber"]);

                int value = convertToInt(Request.Form["comboInstitution"]);

                var mainService = new MainService();
                Institution institution = mainService.LoadInstitution(GetSession(), value);
                doctor.Institution = institution;

                doctor.Sex = convertToNullableInt(Request.Form["comboSex"]);
                doctor.Reject = convertToNullableInt(Request.Form["comboReject"]);
                doctor.Assign = convertToNullableInt(Request.Form["comboConfirm"]);
                var s = Request.Form["comboExpGroup"];
                doctor.GroupExp.Id = convertToInt(s);
                doctor.Address = tfAddress.Text;
                doctor.Data = tfBornYear.Text;
                doctor.Experience = tfExperience.Text;
                doctor.InstitutionAddress = "";
                doctor.Name = tfName.Text;
                doctor.Surname = tfSurname.Text;
                doctor.Patronymic = tfPatronymic.Text;
                string[] d = dataRegistration.Text.Split('.');
                doctor.RegstrationDate = new DateTime(Convert.ToInt32(d[2]), Convert.ToInt32(d[1]), Convert.ToInt32(d[0]));

                FlatEmployee employee = (FlatEmployee) Session["RMRDoctor"];
                if (employee != null) {
                    Session["RMRDoctor"] = null;
                    doctor.Name = employee.Name;
                    doctor.Surname = employee.Surname;
                    doctor.Patronymic = employee.Patromane;
                    var sex = employee.Sex.Trim().ToLower();
                    doctor.Sex = "female" == sex ? 0 : 1;
                    doctor.Data = "" + employee.BearthYear;
                    doctor.Address = employee.Address;
                    doctor.Experience = "" + employee.Experience;
                    bool find = false;
                    JobCategory jc = null;
                    if (!string.IsNullOrWhiteSpace(employee.Speciality)) {
                        var jobcats = mainService.GetJobCategoryList(GetSession(), true);
                        foreach (var jobcat in jobcats) {
                            if (jobcat.Title.ToLower().Equals(employee.Speciality.Trim().ToLower())) {
                                jc = jobcat;
                                break;
                            }
                        }
                        if (jc == null) {
                            var j = new JobCategory() {Title = employee.Speciality.Trim()};
                            jc = mainService.SaveJobCategory(GetSession(), j);
                        }
                    } else {
                        jc = new JobCategory();
                    }
                    {
                        find = false;
                        string title = "отсутствует";
                        if (!string.IsNullOrWhiteSpace(employee.AcademicDegree)) {
                            title = employee.AcademicDegree.Trim().ToLower();
                        }
                        var degreeList = mainService.GetDegreeList(GetSession(), true);
                        foreach (var degree in degreeList) {
                            if (degree.Title.ToLower().Equals(title)) {
                                doctor.Degree = degree;
                                find = true;
                                break;
                            }
                        }
                        if (!find) {
                            var degree = new Degree() {Title = employee.AcademicDegree.Trim()};
                            doctor.Degree = mainService.SaveDegree(GetSession(), degree);
                        }
                    }
                    {
                        find = false;
                        string title = "без категории";
                        if (!string.IsNullOrWhiteSpace(employee.Category)) {
                            title = employee.Category.Trim().ToLower();
                        }
                        var classList = mainService.GetClassList(GetSession(), true);
                        foreach (Class @class in classList) {
                            if (@class.Title.ToLower().Equals(title)) {
                                doctor.OldClass = @class;
                                find = true;
                                break;
                            }
                        }
                    }
                    if (!string.IsNullOrWhiteSpace(employee.Post)) {
                        find = false;
                        var jobList = mainService.GetJobList(GetSession(), true);
                        foreach (var job in jobList) {
                            if (job.Title.ToLower().Equals(employee.Post.Trim().ToLower())) {
                                doctor.Job = job;
                                find = true;
                                break;
                            }
                        }
                        if (!find) {
                            var job = new Job() {JobCategory = jc, Title = employee.Post.Trim()};
                            doctor.Job = mainService.SaveJob(GetSession(), job);
                        }
                    }
                }

            }
            if (doctor.Id == 0 && !IsPostBack) {
                doctor.ContractNumber = ms.GetMaxDoctorContractNumber(GetSession()) + 1;
            }
            if (doctor.Order.Id == 0) {
                linkOrder.NavigateUrl = "";
                linkOrder.Text = "Не включён в приказ";
                // printMenu.NavigateUrl = "";

            } else {
                linkOrder.NavigateUrl = "";// "/forms/Editors/OrderEdit.aspx?id=" + doctor.Order.Id;
                linkOrder.Text = "Приказ №" + doctor.Order.Number;
            }

            if (doctor.Order != null && doctor.Order.Id > 0) {
                printMenu.Controls.Add(
                        new HyperLink() {
                            NavigateUrl = ResolveUrl("~/forms/Reports/Print/Print.aspx?type=" + typeof(PrintExtract) + "&id=" + doctor.Id),
                            //NavigateUrl = ResolveUrl("~/forms/Reports/Extract/ReportExtract.aspx?id=" + doctor.Id),
                            Text = "Выписка",
                            CssClass = "print"
                        });
                printMenu.Controls.Add(
                    new HyperLink() {
                        NavigateUrl = ResolveUrl("~/forms/Reports/Print/Print.aspx?type=" + typeof(PrintAttestatProtocol) + "&id=" + doctor.Id),
                        //NavigateUrl = ResolveUrl("~/forms/Reports/Protocol/ReportAttestatProtocol.aspx?id=" + doctor.Id),
                        Text = "Протокол(Аттестационная комиссия)",
                        CssClass = "print"
                    });
                printMenu.Controls.Add(
                    new HyperLink() {
                        NavigateUrl = ResolveUrl("~/forms/Reports/Print/Print.aspx?type=" + typeof(PrintProfileProtocol) + "&id=" + doctor.Id),
                        //NavigateUrl = ResolveUrl("~/forms/Reports/Protocol/ReportProfileProtocol.aspx?id=" + doctor.Id),
                        Text = "Протокол(Профильная комиссия)",
                        CssClass = "print"
                    });
                printMenu.Controls.Add(
                    new HyperLink() {
                        NavigateUrl = ResolveUrl("~/forms/Reports/Invoice/ReportInvoice.aspx?id=" + doctor.Id),
                        Text = "Квитанция на оплату",
                        CssClass = "print"
                    });
                printMenu.Controls.Add(
                    new HyperLink() {
                        NavigateUrl = ResolveUrl("~/forms/Reports/Print/Print.aspx?type=" + typeof(PrintSertificate) + "&id=" + doctor.Id),
                        //NavigateUrl = ResolveUrl("~/forms/Reports/Sertificate/ReportSertificate.aspx?id=" + doctor.Id),
                        Text = "Удостоверение",
                        CssClass = "print"
                    });

            }

            tfContractNumber.Text = doctor.ContractNumber.ToString();
            dataRegistration.Text = doctor.RegstrationDate.ToShortDateString();
            tfSurname.Text = doctor.Surname;
            tfName.Text = doctor.Name;
            tfPatronymic.Text = doctor.Patronymic;
            tfBornYear.Text = doctor.Data;
            tfAddress.Text = doctor.Address;
            tfExperience.Text = doctor.Experience;

            comboSex.SelectedValue = doctor.Sex != null ? ("" + doctor.Sex) : "null";
            comboConfirm.SelectedValue = doctor.Assign != null ? ("" + doctor.Assign) : "null";
            comboReject.SelectedValue = doctor.Reject != null ? ("" + doctor.Reject) : "null";

            FillCombo(comboAcademicTitle, ms.GetAcademicTitleList(GetSession(), true), doctor.AcademicTitle);
            FillCombo(comboClass, ms.GetClassList(GetSession(), true), doctor.OldClass);
            FillCombo(comboClassNew, ms.GetClassList(GetSession(), true), doctor.NewClass);
            FillCombo(comboDegree, ms.GetDegreeList(GetSession(), true), doctor.Degree);
            FillCombo(comboJob, ms.GetJobList(GetSession(), true), doctor.Job);
            FillCombo(comboJob2, ms.GetJobList(GetSession(), true), doctor.Job2);
            FillCombo(comboInstitution, ms.GetInstitutionList(GetSession(), true), doctor.Institution);
            FillCombo(comboSpec, ms.GetSpecialityList(GetSession(), true), doctor.OldSpeciality);

            Speciality[] specialityList = ms.GetSpecialityList(GetSession(), true);
            Doctor[] doctorListDouble = ms.GetDoctorListDouble(GetSession(), doctor);

            Dictionary<int, DateTime> lastExam = new Dictionary<int, DateTime>();
            for (int i = 0; i < doctorListDouble.Length; i++) {
                int specId = doctorListDouble[i].NewSpeciality.Id;
                DateTime date = doctorListDouble[i].Order.Date;
                if (lastExam.ContainsKey(specId)
                    && lastExam[specId] < date
                    || !lastExam.ContainsKey(specId)) {
                    lastExam[specId] = date;
                }
            }

            foreach (var speciality in specialityList) {
                var item = new ListItem(speciality.Title, "" + speciality.Id);
                item.Attributes["type"] = speciality.GetType().Name;
                item.Text = speciality.Title;
                var date = "";
                if (lastExam.ContainsKey(speciality.Id)) {
                    date = lastExam[speciality.Id].ToShortDateString();
                }else {
                    date = "--.--.----";
                }
                item.Attributes["date"] = date;
                comboSpecNew.Items.Add(item);
            }
            SelectInCombo(comboSpecNew, doctor.NewSpeciality);

            var listItem = new ListItem("- Не выбрана -", "0");
            listItem.Attributes["specialities"] = ";null;";
            comboExpGroup.Items.Add(listItem);
            foreach (var groupExp in ms.GetGroupExpList(GetSession(), true)) {
                var item = new ListItem(groupExp.Group, "" + groupExp.Id);
                item.Attributes["type"] = groupExp.GetType().Name;
                string specs = "";
                foreach (var speciality in groupExp.SpecialityList) {
                    specs += ";" + speciality.Id;
                }
                specs += ";";
                item.Attributes["specialities"] = specs;
                comboExpGroup.Items.Add(item);
            }

            if (id != null) {
                comboExpGroup.SelectedValue = "" + doctor.GroupExp.Id;
            }
            //}
            if (!string.IsNullOrEmpty(hfSelectLpu.Value)) {
                comboInstitution.SelectedValue = hfSelectLpu.Value;
            }
        }

        private static int? convertToNullableInt(object o) {
            if (o == null || Equals(o, "null")) {
                return null;
            }else {
                return convertToInt(o);
            }
        }

        private static int convertToInt(object o) {
            string s = "" + o;
            try {
                return Convert.ToInt32(s);
            }catch(Exception e) {
                return 0;
            }
        }

        private static void FillCombo(ListControl combo, IEnumerable<DirectorySimpleItem> items, DirectorySimpleItem selectedValue) {
            foreach (var item in items) {
                var listItem = new ListItem(item.Title, "" + item.Id);
                listItem.Attributes["type"] = item.GetType().Name;
                combo.Items.Add(listItem);
            }
            SelectInCombo(combo, selectedValue);
        }

        private static void SelectInCombo(ListControl combo, DirectorySimpleItem selectedValue) {
            if (selectedValue != null) {
                try {
                    foreach (ListItem item in combo.Items) {
                        if (item.Value == "" + selectedValue.Id) {
                            combo.SelectedValue = "" + selectedValue.Id;
                            return;
                        }
                    }
                    var listItem = new ListItem("- Не выбрано -", "null");
                    listItem.Attributes["class"]="static";
                    combo.Items.Insert(0, listItem);
                    combo.SelectedValue = "null";
                } finally { }
            }
        }

        private static void FillCombo(ListControl combo, IEnumerable<Institution> items, Institution selectedValue) {
            combo.Items.Add(new ListItem("Не выбрано", "0"));
            foreach (var item in items) {
                var listItem = new ListItem(item.Title, "" + item.Id);
                listItem.Attributes["rmr"] = "" + item.Rmr;
                listItem.Attributes["type"] = item.GetType().Name;
                combo.Items.Add(listItem);
            }
            SelectInCombo(combo, selectedValue);
        }

        protected void btnSave_Click(object sender, EventArgs e) {
            var mainService = new MainService();
            bool create = doctor.Id == 0;
            try {

                doctor.AcademicTitle.Id = Convert.ToInt32(comboAcademicTitle.SelectedValue);
                doctor.OldClass.Id = Convert.ToInt32(comboClass.SelectedValue);
                doctor.NewClass.Id = Convert.ToInt32(comboClassNew.SelectedValue);
                doctor.Degree.Id = Convert.ToInt32(comboDegree.SelectedValue);
                //doctor.Institution.Id = Convert.ToInt32(comboInstitution.SelectedValue);
                doctor.Job.Id = Convert.ToInt32(comboJob.SelectedValue);
                doctor.Job2.Id = Convert.ToInt32(comboJob2.SelectedValue);
                //doctor.Locality.Id = Convert.ToInt32(comboLocality.SelectedValue);
                //doctor.Region.Id = Convert.ToInt32(comboRegion.SelectedValue);
                doctor.OldSpeciality.Id = Convert.ToInt32(comboSpec.SelectedValue);
                doctor.NewSpeciality.Id = Convert.ToInt32(comboSpecNew.SelectedValue);

                int value = Convert.ToInt32(comboInstitution.SelectedValue);

                Institution institution = mainService.LoadInstitution(GetSession(), value);
                doctor.Institution = institution;

                doctor.Sex = int.Parse(comboSex.SelectedValue);
                doctor.Reject = int.Parse(comboReject.SelectedValue);
                doctor.Assign = int.Parse(comboConfirm.SelectedValue);
                //doctor.GroupExp.Id = int.Parse(comboExpGroup.SelectedValue);
                doctor.Address = tfAddress.Text;
                doctor.Data = tfBornYear.Text;
                doctor.Experience = tfExperience.Text;
                doctor.InstitutionAddress = "";
                doctor.Name = tfName.Text;
                doctor.Surname = tfSurname.Text;
                doctor.Patronymic = tfPatronymic.Text;
                int tempVal;
                doctor.ContractNumber = Int32.TryParse(tfContractNumber.Text, out tempVal) ? tempVal : (int?)null;
                string[] d = dataRegistration.Text.Split('.');
                doctor.RegstrationDate = new DateTime(Convert.ToInt32(d[2]), Convert.ToInt32(d[1]), Convert.ToInt32(d[0]));
                doctor = mainService.SaveDoctor(GetSession(), doctor);
                doctor = mainService.LoadDoctor(GetSession(), doctor.Id);
                string s = Request.Url.ToString();
                if (create) {
                    s += "?id=" + doctor.Id;
                }
                var doctorList = (List<Doctor>)Session["docList"];
                if (doctorList != null) {
                    if (!create) {
                        for (int i = 0; i < doctorList.Count; i++) {
                            if (doctorList[i].Id == doctor.Id) {
                                doctorList[i] = doctor;
                            }
                        }
                    } else {
                        doctorList.Insert(0, doctor);
                    }
                    Session["docList"] = doctorList;
                }
                Uri urlReferrer = Request.UrlReferrer;
                if (urlReferrer != null) {
                    string absoluteUri = urlReferrer.AbsoluteUri;
                    //Response.Redirect(absoluteUri);
                }
                Session.Remove("newdoctor");
                Session["success"] = "Изменения сохранены успешно";
            } catch (Exception ex) {

                if (ex.InnerException is SoapException
                    && ((SoapException)ex.InnerException).Detail.InnerText == "AuthorizationException") {
                    throw ex;
                } else {
                    Session["error"] = "Ошибка сохранения";
                }
            }

        }

        protected void btnCancel_Click(object sender, EventArgs e) {
            //Session["info"] = "Изменения отменены";
        }

        protected void hfSelectLpu_ValueChanged(object sender, EventArgs e) {
            var tmp = hfSelectLpu.Value;
        }

    }

}